/**
 * Copyright (c) 2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

Dialog.Picker = new Class(
{
	Extends: Dialog.Base,
	BindsWithEvent: ['hide'],
	
	initialize: function(el, options)
	{
		// picker is attached to an element
		this.el = $(el);
		
		// picker
		var opt = {
			'className':   'picker',
			'autoDisplay': true,
			'setWidth':    true,
			'width':       0
		};
		$extend(opt, options);
		this.parent(opt);
		
		// events
		if (this.options.autoDisplay) {
			this.el.addEvent('focus', this.display.bindWithEvent(this));
		}
	},
	
	display: function(evt)
	{
		this.parent(evt);
		this.dialog.addEvent('outerclick', this.hide);
	},
	
	hide: function(evt)
	{
		if (evt)
		{
			var target = evt.target;
			while(target && target.get('tag') != 'body')
			{
				if (target == this.el)
				{
					evt.stop();
					return;
				}
				target = target.getParent();
			}
		}
		
		this.dialog.removeEvent('outerclick', this.hide);
		this.parent();
	},
	
	_setPosition: function()
	{
		var pos    = this.el.getCoordinates();
		var styles = {
			'position': 'absolute',
			'left': pos.left + 'px',
			'top': (pos.top + pos.height) + 'px'
		};
		if (this.options.setWidth || this.options.width) {
			styles.width = (this.options.width || pos.width) + 'px';
		}
		this.dialog.setStyles(styles);
	},
	
	_injectWindow: function()
	{
		document.body.appendChild(this.window);
	}
});
